package com.woniuxy.project115.kaer.mall.service.impl;

import com.woniuxy.project115.kaer.mall.entity.OrderOfProduct;
import com.woniuxy.project115.kaer.mall.entity.ProductInfo;
import com.woniuxy.project115.kaer.mall.mapper.OrderOfProductMapper;
import com.woniuxy.project115.kaer.mall.mapper.ProductInfoMapper;
import com.woniuxy.project115.kaer.mall.service.OrderOfProductService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;

/**
 * <p>
 * 订单商品数据表 服务实现类
 * </p>
 *
 * @author lyc
 * @since 2025年02月17日
 */
@Service
public class OrderOfProductServiceImpl extends ServiceImpl<OrderOfProductMapper, OrderOfProduct> implements OrderOfProductService {
    @Resource
    private OrderOfProductMapper orderOfProductMapper;
    @Resource
    private ProductInfoMapper productInfoMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public void addToCart(Integer productId, Integer number, Integer userId) throws Exception {
        //判断该商品是否存在
        ProductInfo productInfo = productInfoMapper.selectById(productId);
        if (productInfo == null) {
            throw new RuntimeException("该商品不存在");
        }
        //判断该商品是否已经存在于购物车中
        if (stringRedisTemplate.opsForZSet().score("cart:list:" + userId, productId.toString()) != null) {
            //如果存在，则更新数量
            //判断库存是否充足
            Integer currentNum = Integer.parseInt(stringRedisTemplate.opsForHash().get("cart:info:" + userId+":"+productId, "number").toString());
            System.out.println(currentNum);
            if (currentNum + number > productInfo.getNumber()) {
                throw new Exception("库存不够");
            }
            stringRedisTemplate.opsForHash().increment("cart:info:"+userId+":"+productId,"number", number);
        } else {
            if (number > productInfo.getNumber()) {
                throw new Exception("库存不够");
            }
            //如果不存在，则添加到购物车中
            stringRedisTemplate.opsForZSet().add("cart:list:" + userId, productId.toString(), new Date().getTime());
            //添加到购物车的具体商品信息中
            HashMap<Object, Object> map = new HashMap<>();
            map.put("productId", productId+"");
            map.put("number", number+"");
            stringRedisTemplate.opsForHash().putAll("cart:info:"+userId+":"+productId,map);
        }
    }
}
